package com.pfsoft.grpcserver.grpc.impl;

import com.google.protobuf.Empty;
import com.pfsoft.grpc.common.types.Common;
import com.pfsoft.grpc.order.api.*;
import com.pfsoft.grpcserver.domain.TbOrderInfo;
import com.pfsoft.grpcserver.service.IOrderInfoService;
import io.grpc.stub.StreamObserver;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.server.service.GrpcService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author pengfei
 * @date 2022年06月29日 18:25
 */
@Slf4j
@GrpcService
@Service
public class OrderInfoGrpc extends OrderInfoServiceGrpc.OrderInfoServiceImplBase {

    @Autowired
    private IOrderInfoService orderInfoService;

    @Override
    public void saveOrderInfo(SaveOrderInfoRequest request, StreamObserver<Common.SimpleResponse> responseObserver) {
//        log.debug("saveOrderInfo request params is: 【{}】",request);

        OrderInfo orderInfo = request.getOrderInfo();

        TbOrderInfo tbOrderInfo=new TbOrderInfo();
        BeanUtils.copyProperties(orderInfo,tbOrderInfo);
        tbOrderInfo.setAmount(new BigDecimal(orderInfo.getAmount()));
        int save = orderInfoService.save(tbOrderInfo);

        Common.SimpleResponse response = Common.SimpleResponse.newBuilder().setStatus(201).build();
        responseObserver.onNext(response);
        responseObserver.onCompleted();

    }

    @Override
    public void queryOrderInfo(queryOrderInfoRequest request, StreamObserver<QueryOrderInfoResponse> responseObserver) {
        super.queryOrderInfo(request, responseObserver);
    }

    @Override
    public void listOrderInfo(Empty request, StreamObserver<ListOrderInfoResponse> responseObserver) {
//        log.debug("begin list all orderInfo ");
        List<TbOrderInfo> all = orderInfoService.getAll();
        List<OrderInfo> orderInfoList = all.parallelStream().map(this::toTbOrderInfo).collect(Collectors.toList());
        ListOrderInfoResponse response = ListOrderInfoResponse.newBuilder().addAllOrderInfoList(orderInfoList).build();
        responseObserver.onNext(response);
        responseObserver.onCompleted();
//        log.debug("end list all orderInfo");
    }

    /**
     * tbOrderInfo convert to OrderInfo
     * @param tbOrderInfo
     * @return
     */
    private OrderInfo toTbOrderInfo(TbOrderInfo tbOrderInfo){
        return OrderInfo.newBuilder().
                setOrderId(tbOrderInfo.getOrderId())
                .setAmount(tbOrderInfo.getAmount().doubleValue())
                .setPhone(tbOrderInfo.getPhone())
                .setReceiver(tbOrderInfo.getReceiver()).build();
    }


}
